package org.bank;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.bank.dto.AccountTO;

/**
 * Servlet implementation class BankServlet
 */
public class BankServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private BankDelegate bank;

	@Override
	public void init() throws ServletException {
		bank = new BankDelegate();
		super.init();
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BankServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	//Here we create an account with the data received from the client.
	private void doCreate(HttpServletRequest request,
			HttpServletResponse response, String requestingURL)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		AccountTO accountTO = new AccountTO();
		accountTO.ID = Integer.parseInt(request.getParameter("accountID"));
		accountTO.firstName = request.getParameter("firstName");
		accountTO.lastName = request.getParameter("lastName");
		accountTO.address = request.getParameter("address");
		accountTO.phone = request.getParameter("phone");
		double balance = 0;
		String createResp = null;
		try{
			balance = Double.parseDouble(request.getParameter("balance"));
			if(balance<=0)
				throw new Exception();
		}catch(Exception ex){
			createResp = "Balance must be a positive numerical value.";
		}
		if(createResp == null){
			accountTO.balance = balance;
			createResp = bank.createAccount(accountTO);
		}
		session.setAttribute("BankServlet.createResponse", createResp);
		String url = "/" + requestingURL;
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	//we do the search for edit functions and search function. 
	private void doEditSearch(HttpServletRequest request,
			HttpServletResponse response, String requestingURL)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		AccountTO accountTO = null;
		try {
			accountTO = bank.getAccount(Integer.parseInt(request
					.getParameter("accountNumber")));
		} catch (Exception ex) {
		}
		if (accountTO != null) {
			session.setAttribute("BankServlet.createResponse", accountTO); //we return as a response a TO
		} else {

			session.setAttribute("BankServlet.createResponse",
					"Account non existent."); //if the account does not exist, we return a string.
			session.setAttribute("Status", new Object());
		}
		String url = "/" + requestingURL;
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	//we save the changes requested by the client.
	private void doEdit(HttpServletRequest request,
			HttpServletResponse response, String requestingUrl)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String createResp = bank.editAccount(
				Integer.parseInt(request.getParameter("accountID")),
				request.getParameter("firstName"),
				request.getParameter("lastName"),
				request.getParameter("address"),
				request.getParameter("phoneNumber"));

		session.setAttribute("BankServlet.createResponse", createResp);
		session.setAttribute("Status", new Object());
		String url = "/" + requestingUrl;
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	//this method deals with generating a response for the case of money transfer request.
	private void doTransfer(HttpServletRequest request,
			HttpServletResponse response, String requestingURL)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		int account1 = 0, account2 = 0;
		double amount = 0;
		String createResponse = null;
		try {
			account1 = Integer.parseInt(request.getParameter("accountNumber1")); // validation
		} catch (Exception ex) {
			createResponse = "Account number 1 should be an integer value.";
		}
		try {
			account2 = Integer.parseInt(request.getParameter("accountNumber2"));// validation
		} catch (Exception ex) {
			createResponse = "Account number 2 should be an integer value.";
		}
		try {
			amount = Double.parseDouble(request.getParameter("amount"));// validation
			if (amount < 0)
				throw new Exception();
		} catch (Exception ex) {
			createResponse = "Amount must be a positive numerical value.";
		}
		if (createResponse == null) { //everything was entered correctly
			createResponse = bank.transferMoney(account1, account2, amount);
		}
		session.setAttribute("BankServlet.createResponse", createResponse);
		session.setAttribute("Status", new Object());
		String url = "/" + requestingURL;
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	//generating response for POST submissions
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action.equals("CREATE")) {
			doCreate(request, response, "create.jsp");
		}
		if (action.equals("EDIT_SEARCH")) {
			doEditSearch(request, response, "edit.jsp");
		}
		if (action.equals("EDIT")) {
			doEdit(request, response, "edit.jsp");
		}
		if (action.equals("SEARCH")) {
			doEditSearch(request, response, "index.jsp");
		}
		if (action.equals("TRANSFER")) {
			doTransfer(request, response, "transfer.jsp");
		}
	}

}